<?php
/**
 * Author: LaiGuiming
 * Time: 2017-11-29 15:40:12
 * Copyright (C) 2016 Longyan Wehome Message CO.,LTD.
 */

namespace app\admin\controller\sys;
use app\common\controller\BackEnd;

/**
 * 数据字典控制器
 * Class Dict
 * @package app\admin\controller
 */
class Dict extends BackEnd
{
    protected $model;//模型对象
    protected $modelName;//模型名称
    protected $explain;//说明

    public function _initialize()
    {
        parent::_initialize();
        $this->model=D("dict");
        $this->modelName="Dict";
        $this->explain="数据字典";
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/save/del/loadData五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将app/admin/lib/traits/Crud.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 获取分页数据 bootstrap-table格式
     * @param int $limit
     * @param int $offset
     */
    public function loadData($limit = 10,$offset=0)
    {
        $where="status!=2";
        $where=$this->getCondition($where,"name","like");
        if(input("type_id")){
            $where.=" and type_id=".input("type_id");
        }else{
            $where.=" and type_id=0";
        }

        $counts=$this->model->where($where)->count();
        $data=$this->model->where($where)->order('ct desc')->limit($offset,$limit)->select();

        $res = array("rows" => $data, "total" => $counts);
        echo json_encode($res);
    }

    /**
     * 删除
     * @param string $id
     */
    public function del($id = '')
    {
        $list=$this->model->all(explode(',', $id));
        foreach ($list as $temp){
            cache($temp['code'],null);
        }

        $this->model->where('id in ('.$id.')')->update([ 'status' => 2]);
        $this->saveLog("删除".$this->explain."【".$id."】");
        $this->resSuccess();
    }

    /**
     * 保存
     * @param string $id
     * @return string|void
     */
    public function save($id = '')
    {
        //校验
        $validate=validate($this->modelName);
        if(!$validate->check($_POST)){
            $this->resError($validate->getError());
            return;
        }

        if ($id != '') {
            $res = $this->model->allowField(true)->save($_POST,['id' => $id]);
            $this->saveLog("修改".$this->explain."【".$id."】");
        }else{
            $res = $this->model->allowField(true)->save($_POST);
            $this->saveLog("新增".$this->explain."【".$this->model->id."】");
        }
        cache($_POST['code'],$_POST['val']);
        $this->resData($res);
    }
}